<?php
//$Id: cache.php 201 2012-03-13 07:21:44Z tomqin@gmail.com $

/**
 * Cache 缓存操作类
 *
 * @copyright		Copyright (C) 2010-2012 ARESCMS Inc.
 * @author			TomQin <tomqin@gmail.com>
 * @license			http://www.arescms.cn/license/
 * @package Core
 */

final Class Cache
{
	/**
	 * Get a cache data
	 *
	 * @param string
	 * @param integer
	 * @return mixed
	 */
	public static function get($name, $cache_time = 0) {
		static $cache = array();

		$key = md5(strtolower($name));
		if(!isset($cache[$key])){
			$cache[$key] = self::_get_cache($key, $cache_time);
		}
		return $cache[$key];
	}

	public static function set($name, $data) {
		$key = md5(strtolower($name));
		$file = self::_cache_file($key);
		$dir  = dirname($file);
		if(!is_dir($dir))
			mkdir($dir, 0777, true);
		return file_put_contents($file, serialize($data));
	}

	private static function _get_cache($key, $cache_time = 0) {
		$file = self::_cache_file($key);
		if(!is_file($file)){
			return null;
		}
		if($cache_time && TIMESTAMP - filemtime($file) > $cache_time) {
			return null;
		}else{
			if(is_file($file)){
				return unserialize(file_get_contents($file));
			}else{
				return null;
			}
		}
	}

	private static function _cache_file($key){
		return DATA_PATH . 'cache' .DS. $key{0} .DS. $key{1} .DS. $key{2} .DS. $key.'.dat';
	}
}
?>